<?php

namespace App\Admin\Controller\Base;

use App\AbstractController;
use App\Admin\Service\Base\RoleService;
use App\Admin\Service\Base\RouteService;
use App\Common\Exception\ApiMessageException;
use App\Common\Model\Base\Role;
use App\Common\Util\Response;
use App\Common\Util\TP;
use Psr\SimpleCache\InvalidArgumentException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 管理员角色控制器
 */
class RoleController extends AbstractController
{

    /**
     * 列表页
     *
     * @return string
     */
    public function lists(): string
    {
        return Response::render('Base/Role/lists');
    }

    /**
     * 列表数据
     *
     * @return \think\Response
     * @throws InvalidArgumentException
     */
    public function listsData(): \think\Response
    {
        return Response::json()->success(RoleService::aop()->lists());
    }

    /**
     * 创建数据页面
     *
     * @return string
     */
    public function create(): string
    {
        return Response::render('Base/Role/edit');
    }

    /**
     * 创建数据
     *
     * @return \think\Response
     * @throws ApiMessageException
     */
    public function store(): \think\Response
    {
        RoleService::aop()->store($this->request->post());

        return Response::json()->success();
    }

    /**
     * 更新数据页面
     *
     * @return string
     */
    public function edit(): string
    {
        return Response::render('Base/Role/edit');
    }

    /**
     * 更新数据
     *
     * @return \think\Response
     * @throws ApiMessageException
     * @throws InvalidArgumentException
     */
    public function update(): \think\Response
    {
        RoleService::aop()->update($this->request->post());

        return Response::json()->success();
    }

    /**
     * 删除数据
     *
     * @return \think\Response
     * @throws ApiMessageException
     */
    public function destroy(): \think\Response
    {
        RoleService::aop()->destroy($this->request->post('ids'));

        return Response::json()->success();
    }

    /**
     * 设置权限
     *
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setPermission(): string
    {
        return Response::render('Base/Role/setPermission', [
            'route'   => RouteService::aop()->lists()['data'],
            'default' => Role::find(TP::request()->get('id'))?->route_ids ?: []
        ]);
    }

    /**
     * 设置权限
     *
     * @return \think\Response
     * @throws ApiMessageException
     * @throws InvalidArgumentException
     */
    public function savePermission(): \think\Response
    {
        RoleService::aop()->savePermission(
            (int)TP::request()->get('id'),
            (array)TP::request()->post('route_ids')
        );

        return Response::json()->success();
    }
}
